package com.lt.crm.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lt.crm.mapper.SysRightMapper;
import com.lt.crm.pojo.SysRight;
import com.lt.crm.pojo.SysRole;
import com.lt.crm.pojo.SysRoleRight;
import com.lt.crm.pojo.SysUser;
import com.lt.crm.service.SysRightService;
import com.lt.crm.service.SysRoleRightService;
import com.lt.crm.service.SysRoleService;
import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;


import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/role")
public class SysRoleController {

    @Resource
    SysRoleService sysRoleService;

    @Resource
    SysRightService sysRightService;

    @Resource
    SysRoleRightService sysRoleRightService;

    @GetMapping("/json")
    @ResponseBody
    public List<SysRole> role() {
        return sysRoleService.list();
    }

    @RequestMapping("/list")
    public String list(@RequestParam(required = false, defaultValue = "") String roleName,
                       @RequestParam(required = false, defaultValue = "1") Integer pageIndex,
                       Model model) {
//        Sort sort = new Sort(Sort.Direction.ASC, "roleId");
//        Pageable pageable = PageRequest.of(pageIndex - 1, 3, sort);
//        Page<Role> rolePage = roleService.findRole(roleName, pageable);


        Page<SysRole> page = new Page<>(pageIndex, 5); // pageIndex从1开始，MyBatis-Plus会自动减1
        Page<SysRole> rolePage =sysRoleService.findRole(roleName,page);
        model.addAttribute("rolePage", rolePage);
        model.addAttribute("roleName", roleName);//保存查询条件
        return "role/list";
    }

    @RequestMapping("/add")
    public String add(Model model) {
        // 查找所有权限，用于指派授权
        List<SysRight> rights = sysRightService.findAllRights();
        model.addAttribute("rights", rights);
        return "role/add";
    }

    @RequestMapping("/edit")
    public String edit(Integer roleId, Model model) {
        SysRole role = sysRoleService.getById(roleId);
        model.addAttribute("role", role);
        // 查找角色权限
        List<SysRight> roleRights = sysRoleService.findRightsByRole(role);
        model.addAttribute("roleRights", roleRights);
        // 查找所有权限，用于指派权限
        List<SysRight> rights = sysRightService.findAllRights();
        model.addAttribute("rights", rights);
        return "role/edit";
    }

    @RequestMapping("/doEdit")
    @Transactional // 确保整个方法在一个事务中
    public String doEdit(SysRole role, @RequestParam("rightCodes") List<String> rightCodes) {
        // 假设sysRoleService有一个根据ID更新角色的方法
        if (role.getRoleId() != null) {
            // 更新角色信息（确保你有这样的方法）
            sysRoleService.updateById(role); // 假设存在updateById方法
        }

        // 清除旧的角色权限关联（可选，取决于业务需求）
        QueryWrapper<SysRoleRight> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("rf_role_id", role.getRoleId());
        sysRoleRightService.remove(queryWrapper); // 使用remove方法进行删除

        // 插入新的角色权限关联
        for (String rightCode : rightCodes) {
            SysRoleRight sysRoleRight = new SysRoleRight();
            sysRoleRight.setRfRightCode(rightCode);
            sysRoleRight.setRfRoleId(role.getRoleId());
            sysRoleRightService.save(sysRoleRight); // 假设存在save方法
        }

        return "redirect:/role/list";
    }




    @RequestMapping("/save")
    public String save(SysRole role, String[] rightCodes) {
        if (rightCodes != null) {
            for (String rightCode : rightCodes) {

                SysRight right = new SysRight();
                right.setRightCode(rightCode);

                List<SysRight> rights = sysRightService.findRightsByRole(role);
                role.setRights(rights);
                //role.setRights();
                role.getRights().add(right);//将关联的权限添加到角色中，用于级联新增关联表的数据
            }
        }

        //roleService.saveRole(role);//新增，会级联新增关联表的数据
        sysRoleService.saveOrUpdate(role);
        return "redirect:/role/list";//增删改之后跳转最好使用重定向
    }

    @RequestMapping("/doAdd")
    public String doAdd(SysRole role,@RequestParam("rightCodes") List<String>  rightCodes) {
        boolean save = sysRoleService.save(role);
        if(rightCodes != null) {
            SysRoleRight sysRoleRight;
            for (String rightCode : rightCodes) {
                sysRoleRight = new SysRoleRight();
                sysRoleRight.setRfRightCode(rightCode);
                sysRoleRight.setRfRoleId(role.getRoleId());
                sysRoleRightService.save(sysRoleRight);
            }
        }
        return  "redirect:/role/list";
    }



    @RequestMapping("/del/{roleId}")
    @ResponseBody
    public Map del(@PathVariable Integer roleId) {
        Map<String,String> map = new HashMap();
        try {
//            QueryWrapper<SysRoleRight> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("rf_role_id", roleId);
//            sysRoleRightService.remove(queryWrapper);
   //         sysRoleService.removeById(roleId);
            sysRoleService.deleteRole(Long.valueOf(roleId));
            map.put("delResult", "true");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("delResult", "false");
        }
        return map;
    }

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @RequestMapping("/backList")
    public String backList(Model model,@RequestParam(required = false, defaultValue = "") String roleName,
                           @RequestParam(required = false, defaultValue = "1") Integer pageIndex) {

        ValueOperations<String, String> valueOps = redisTemplate.opsForValue();
        List<SysRole> roles = new ArrayList<>(); // 创建一个SysRole列表来存储结果
        Set<String> keys = redisTemplate.keys("deletedRoleData:*");
        for (String key : keys) {
            // 移除前缀并获取ID
            String idStr = key.replaceFirst("deletedRoleData:", "");
            Long id = Long.parseLong(idStr);
            // 查询Redis中的角色数据
            String roleJson = valueOps.get(key);
            ObjectMapper objectMapper = new ObjectMapper();
            try {

                if (roleJson != null) {
                    // 注意这里应该是反序列化单个SysRole对象，而不是List<SysRole>
                    SysRole role = objectMapper.readValue(roleJson, SysRole.class);
                    roles.add(role); // 将反序列化后的SysRole对象添加到列表中
                }

            } catch (IOException e) {
                // 处理异常，例如记录日志或返回错误
                e.printStackTrace();
            }
        }
//        Page<SysRole> page = new Page<>(pageIndex, 5); // pageIndex从1开始，MyBatis-Plus会自动减1
//        Page<SysRole> rolePage =sysRoleService.findRole2(roleName,null);
        model.addAttribute("rolePage", roles);
        model.addAttribute("roleName", roleName);//保存查询条件

        return "/role/back";

    }

    @RequestMapping("/back/{roleId}")
    @ResponseBody
    public Map back(@PathVariable Integer roleId) {
        Map<String,String> map = new HashMap();
        try {
            sysRoleService.restoreRole(Long.valueOf(roleId));
            map.put("delResult", "true");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("delResult", "false");
        }
        return map;
    }



    @RequestMapping("/delCache/{roleId}")
    @ResponseBody
    public Map delCache(@PathVariable Integer roleId) {
        Map<String,String> map = new HashMap();
        try {
            sysRoleService.deleteRoleCache(Long.valueOf(roleId));
            map.put("delResult", "true");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("delResult", "false");
        }
        return map;
    }



}
